package org.example.interceptor;

import org.example.rvo.ResultVO;
import org.example.util.JSONUtil;
import org.example.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 针对login请求进行判断token是否存在的
 * 1.如果不存在，说明里面没有token 直接跳到执行登录登录操作
 * 2.如果里面包含token，然后判断token是否过期，如果没有过期，直接返回无需二次登录
 *                                        如果过期，在跳回到登录操作
 * @author jianma
 */
public class LoginTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        System.out.println("-------------------------");
        //从前端传入的header的token key中判断是否有值
        String token = request.getHeader("token");
        if(token != null ){
            PrintWriter out = response.getWriter();
            //token过期和没过期的判断
            boolean b = JWTUtil.checkToken(token);
            if(b){
                out.write(JSONUtil.obj2str(ResultVO.success("100010","用户已登录，无需二次登录",token)));
                out.flush();
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
